<?php

namespace App\Admin\Controllers;

use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Sharp;
use App\Models\SharpToGoods;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Route;

class SharpController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '秒杀活动';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Sharp());
        
        //$grid->column('store_id', __('Store id'));
	    $time = Carbon::now();
        $grid->column('active_name', '活动名称');
        $grid->column('active_start', '活动开始时间')->sortable();
        $grid->column('active_end', '活动结束时间')->sortable();
        $grid->column('created_at', __('Created at'))->sortable();
        
        $grid->column('status', '活动状态')->display(function ($item) use($time){
            $status =  (new Sharp())->forceFill($this->toArray())->status;
            if ($status[0] < $time && $status[1] > $time) {
                return '进行中';
            } else {
            	return '未进行';
            }
        });
		
        $grid->filter(function (Grid\Filter $filter) {
        	$filter->disableIdFilter();
        	$filter->like('active_name', '活动名称');
        	$filter->between('active_start', '活动开始时间')->datetime();
        	$filter->between('active_end', '活动结束时间')->datetime();
        });
        
        return $grid;
    }
    
	/**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Sharp::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('store_id', __('Store id'));
        $show->field('active_name', __('Active name'));
        $show->field('active_start', __('Active start'));
        $show->field('active_end', __('Active end'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Sharp());

        $form->hidden('store_id', __('Store id'))->default(Admin::user()->store_id);
        $form->text('active_name', '活动名称')->required();
        $form->datetime('active_start', '活动开始时间')
	        ->default(date('Y-m-d H:i:s'))->rules(['required']);
        $form->datetime('active_end', '活动结束时间')
	        ->default(date('Y-m-d H:i:s'))->rules('required|after:active_start');
        $form->textarea('des', '说明(本说明仅管理者可见)')->default('活动开始前添加秒杀商品，活动开始后暂不允许修改，活动结束后自动返回剩余库存')->disable();
        
        $form->ignore(['des']);
        
		$form->saved(function ($form) {
		  if (Route::currentRouteName() === 'sharps.update') {
            admin_toastr('修改成功', 'success');
            return redirect()->route('sharps.edit', ['sharp' => $form->model()->id]);
          }
		});
        
        return $form;
    }
    
	/**
	 * // 修改活动商品会先返回库存然后删除关联，最后重新创建
	 * @param $form
	 */
	protected function returnStock($form)
	{
			$sharpToGoods = SharpToGoods::where('sharp_id', $form->model()->id)->get();
			$goods_id = $sharpToGoods->groupBy('goods_id');
			$goods = Goods::whereIn('id', $goods_id)->whereNull('goods_sku')->get();
			$sku = GoodsSku::whereIn('goods_id', array_keys($goods->groupBY('goods_id')))->get();
			$returns = [];
			SharpToGoods::returnStock($sku, $returns);
			SharpToGoods::returnStock($goods, $returns);
			SharpToGoods::where('sharp_id', $form->model()->id)->forceDelete();
	}
}
